<route lang="json5">
{
  style: {
    navigationBarTitleText: '订场详情',
  },
}
</route>
<template>
  <view class="p-4 box-border flex flex-col h-full">
    <view class="flex-1 overflow-auto">
      <!-- 提示文本 -->
      <!-- <wd-notice-bar text="提交订单即代表认可并遵守《订场须知》和《运动须知》" prefix="warn-bold" /> -->
      <!--日期选择器 粘性布局 -->
      <view class="left-0 top-0 sticky z-10 bg-white">
        <scroll-view
          scroll-x
          class="whitespace-nowrap mb-3 h-auto"
          :show-scrollbar="false"
          enhanced
        >
          <view class="inline-flex">
            <view
              v-for="item in dateList"
              :key="item.date"
              class="inline-flex flex-col items-center justify-center w-[76px] h-[76px] cursor-pointer mr-3 rounded-xl transition-all duration-300 relative"
              :class="[
                model.bookingDate === item.applyPeriod
                  ? 'bg-gradient-to-b from-orange-50 to-orange-100 shadow-sm'
                  : 'bg-gray-50/80 hover:bg-gray-100/90',
              ]"
              @tap="handleDateSelect(item)"
            >
              <text
                class="text-base font-medium mb-1"
                :class="
                  model.bookingDate === item.applyPeriod ? 'text-orange-500' : 'text-gray-700'
                "
              >
                {{ item.weekday }}
              </text>
              <text
                class="text-xs font-medium"
                :class="
                  model.bookingDate === item.applyPeriod ? 'text-orange-400' : 'text-gray-500'
                "
              >
                {{ item.date }}
              </text>
              <view
                v-if="model.bookingDate === item.applyPeriod"
                class="absolute -bottom-1 w-2 h-2 rounded-full bg-orange-500"
              ></view>
            </view>
          </view>
        </scroll-view>
      </view>

      <view class="mt-4 bg-white rounded-xl shadow-sm">
        <basic-table
          :columns="bookingRuleColumns"
          :data="tableData"
          align="center"
          :header-row-style="{ backgroundColor: '#fafafa' }"
          headerRowClassName="basic-table-header"
        >
          <template #item="{ column, scope }">
            <view
              v-if="column.fieldName !== 'timeDivision'"
              class="h-6 flex items-center justify-center mx-1 rounded transition-all box-border px-2 py-1"
              :class="[BOOKING_STATUS[scope[column.fieldName].status].color]"
              @click="handleCellClick(column, scope)"
            >
              <text class="text-sm" v-if="scope[column.fieldName].price">
                {{ scope[column.fieldName].price }}
              </text>
            </view>
          </template>
        </basic-table>

        <!-- 图例 -->
        <view class="flex-between px-4 py-3 text-xs border-t border-gray-100">
          <view class="flex gap-4 justify-center">
            <view
              class="flex items-center gap-1"
              v-for="(status, key) in BOOKING_STATUS"
              :key="key"
            >
              <view :class="['w-4 h-4 rounded', status.color]" />
              <text>
                {{ status.label }}
              </text>
            </view>
          </view>
          <view class="text-gray-400 text-center">单次最多可选2个场次</view>
        </view>
      </view>
    </view>

    <!-- 底部固定按钮 -->
    <view class="pt-3 bg-white">
      <view class="mb-3 flex items-center">
        <wd-checkbox v-model="model.agreement" prop="agreement">
          我已阅读并同意
          <text class="text-orange-500">《购票须知》</text>
          和
          <text class="text-orange-500">《免责声明》</text>
        </wd-checkbox>
      </view>
      <!-- 底部按钮 -->
      <view class="flex items-center justify-between bg-white border-t border-gray-100">
        <view class="flex items-baseline">
          <text class="text-sm text-gray-600">总计：</text>
          <text class="text-xl font-semibold text-orange-500">¥{{ totalPrice }}</text>
        </view>
        <wd-button
          type="primary"
          :loading="loading"
          class="min-w-[120px] h-[40px] font-medium rounded-full"
          @click="handleSubmit"
        >
          确认购票
        </wd-button>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import currency from 'currency.js'
import { debounce } from 'xe-utils'
import dayjs from 'dayjs'
import {
  bookingListRule,
  bookingDetails,
  submitBooking,
  bookingListOutBooking,
} from '@/service/index/subscribe' // 看这里
import { generateTimeSlots, isBookingWithinStoreHours } from '@/utils/common'
import { useToast } from 'wot-design-uni/components/wd-toast'
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
const { userInfo } = storeToRefs(useUserStore())
const toast = useToast()
// 常量大写
const BOOKING_STATUS = {
  0: { label: '不可选', color: 'bg-gray-300 text-gray-500 cursor-not-allowed' },
  1: {
    label: '可预约',
    color: 'bg-green-400 border border-green-800 text-white', // 深绿色背景，白色文字，绿色边框
  },
  2: {
    label: '已预订',
    color: 'bg-red-500 text-white line-through', // 深红色背景，白色文字，划线效果
  },
  3: {
    label: '已选择',
    color: 'bg-blue-500 border border-blue-700 text-white shadow-lg', // 深蓝色背景，白色文字，蓝色边框和阴影
  },
}

const model = ref({
  bookingDate: '', // 预订日期
  khUserId: userInfo.value.id, // 客户ID
  obpId: '', // 订场类价格id
  obzId: '', // 订场周期id
  vobId: '', // 	订场类id
  agreement: false, // 协议同意
})

// 获取订单详情接口
const bookingDetailsData = ref({})
const getBookingDetails = () => {
  bookingDetails({
    id: model.value.vobId,
  }).then((res) => {
    if (res.code === 0) {
      bookingDetailsData.value = res.data || {}
      getBookingRule()
    }
  })
}

// 获取订单规则
const bookingListRuleData = ref([])
const getBookingRule = () => {
  uni.showLoading({ title: '重新加载中...' })

  const params = dateList.value.find((item) => item.applyPeriod === model.value.bookingDate)
  bookingListRule({
    period: params.weekday,
    vobId: model.value.vobId,
  })
    .then((res) => {
      if (res.code === 0) {
        bookingListRuleData.value = res.data || []

        getBookingListOutBooking()
      }
    })
    .finally(() => {
      uni.hideLoading()
    })
}

// 获取已定场次
const bookingListOutBookingData = ref({})
const tableData = ref([])
const bookingRuleColumns = ref([])
const getBookingListOutBooking = () => {
  const prIdList = bookingListRuleData.value.map((item) => item.placeRoomVo.id)
  bookingListOutBooking({
    prIdList,
    bookingDate: model.value.bookingDate,
  }).then((res) => {
    if (res.code === 0) {
      bookingListOutBookingData.value = res.data.reduce((pro, cur) => {
        pro[`${cur.prId}-${cur.startTime}-${cur.endTime}`] = 2
        return pro
      }, {})
      const { startTime, endTime, oneTime } = bookingDetailsData.value
      // 把小时转化为分钟
      const oneTimeMinutes = oneTime
      const timeSlots = generateTimeSlots(startTime, endTime, oneTimeMinutes)
      // 表格相关
      bookingRuleColumns.value = [
        {
          fieldName: 'timeDivision',
          fieldDesc: '',
          width: '100',
          fixed: 'left',
        },
      ]
      tableData.value = timeSlots.map((item, index) => {
        return {
          ...item,
          ...bookingListRuleData.value.reduce((pro, cur) => {
            const priceParams = cur.bookingPriceVoList.find((price) => {
              return isBookingWithinStoreHours(
                item.startTime,
                item.endTime,
                price.applyStartTime,
                price.applyEndTime,
              )
            })
            // 只循环一次
            if (index === 0) {
              bookingRuleColumns.value.push({
                fieldName: cur.placeRoomVo.id,
                fieldDesc: cur.placeRoomVo.roomName,
                width: '60',
                fieldType: 'slot',
              })
            }

            const startTime = `${model.value.bookingDate}${item.startTime}`
            const endTime = `${model.value.bookingDate}${item.endTime}`

            pro[cur.placeRoomVo.id] = {
              prId: cur.placeRoomVo.id, // 场地id
              roomName: cur.placeRoomVo.roomName, // 场地名称
              vobId: cur.vobId, // 订场类id
              obzId: '', // 订场周期id
              startTime,
              endTime,
              khUserId: model.value.khUserId, // 客户id
              bookingDate: model.value.bookingDate, // 订场时间
              obpId: priceParams ? priceParams.id : '', // 订场类价格id
              price: priceParams ? currency(priceParams.price).divide(100).value : 0, // 价格
              status: priceParams
                ? bookingListOutBookingData.value[`${cur.prId}-${startTime}-${endTime}`] || 1
                : 0, // 状态
            }
            return pro
          }, {}),
        }
      })
    }
  })
}

const today = dayjs()

// 日期列表
const dateList = computed(() => {
  const dates = []

  for (let i = 0; i < 7; i++) {
    const date = today.add(i, 'day')
    const weekday = date.format('dddd') // 获取星期几
    const displayWeekday = weekday.replace('星期', '周') // 显示用的周几
    // 只添加可用的日期
    dates.push({
      date: date.format('MM-DD'),
      weekday: displayWeekday,
      fullDate: date.format('YYYY-MM-DD'),
      applyPeriod: date.format('YYYYMMDD'),
    })
  }
  return dates
})

// 处理日期选择
const handleDateSelect = (item: any) => {
  model.value.bookingDate = item.applyPeriod
  getBookingRule()
}

// 处理单元格点击
const handleCellClick = (column, scope) => {
  if (column.fieldName !== 'timeDivision') {
    console.log(scope[column.fieldName].status)

    if (scope[column.fieldName].status === 1) {
      scope[column.fieldName].status = 3
    } else {
      if (scope[column.fieldName].status === 3) {
        scope[column.fieldName].status = 1
      }
    }
  }
}

// 获取路由参数
onLoad((query: any) => {
  model.value.vobId = query.id

  // 默认选择第一个日期
  model.value.bookingDate = dateList.value[0].applyPeriod
  // 初始化时设置第一个场地的ID
  getBookingDetails()
})

// 计算总价
const totalPrice = computed(() => {
  let total = currency(0)
  tableData.value.forEach((row) => {
    Object.keys(row).forEach((key) => {
      if (key !== 'timeDivision' && row[key].status === 3) {
        total = currency(total).add(row[key].price)
      }
    })
  })
  return total
})

// 提交订场
const loading = ref(false)
const handleSubmit = debounce(() => {
  // TODO: 处理提交逻辑
  if (!model.value.agreement) {
    uni.showToast({
      title: '请同意购票须知和免责声明',
      icon: 'none',
    })
    return
  }

  // 如果没有登录就要跳转到登录页
  if (!userInfo.value.id) {
    uni.navigateTo({
      url: '/pages/login/login',
    })
    return
  }

  const selectedPriceList = []
  tableData.value.forEach((item) => {
    Object.keys(item).forEach((key) => {
      if (item[key].status === 3) {
        selectedPriceList.push({ ...item[key], khUserId: userInfo.value.id })
      }
    })
  })

  if (!selectedPriceList.length) {
    uni.showToast({
      title: '请选择订场',
      icon: 'none',
    })
    return
  }

  loading.value = true

  submitBooking(selectedPriceList)
    .then((res) => {
      if (res.code === 0) {
        toast.success('提交成功')

        // 跳转到订单详情页面去支付
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/order/details?id=' + res.data[0].orderPayNo,
          })
        }, 1000)
      } else if (res.code === 540) {
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login',
          })
        }, 1000)
      } else {
        toast.warning(res.msg)
      }
    })
    .finally(() => {
      loading.value = false
    })
}, 300)
</script>

<style lang="scss" scoped>
:deep {
  .base-table .base-table-inner .b-table .b-th .b-cell,
  .base-table .base-table-inner .b-table .b-td .b-cell {
    padding: 0;
  }
}
</style>
